<script>
import { ElMessage } from 'element-plus';

export default {
    name: "SignUp",
    data() {
        return {
            account: '',
            password: '',
            confirm: '',
            nickname: '',
        }
    },
    methods: {
        register(){
            //对account和password进行非空检查和格式检查
            
            //对两次密码是否一致进行检查
            if(this.password != this.confirm){
                ElMessage({
                    message: '警告:两次输入的密码不一致!',
                    type: 'warning',
                })
                return;
            }
            //检查账号(即登录名称)是否被占用
            const url = `/back/customer/usable/${this.account}`;
            this.axios.get(url).then(resp => {
                const { success, message } = resp.data;
                // 若返回的 success 为 true 则表示可以注册
                if( success ) {
                    const data = {
                        account: this.account,
                        password: this.password,
                        nickname: this.nickname
                    }
                    // 将 account、password、nickname 发送到后端完成注册
                    return this.axios.post('/back/customer/sign/up', data)
                }
                ElMessage({ message: `警告:${message}!`, type: 'warning'})
            }).then( resp => {
                if( resp ) {
                    const { success, message } = resp.data;
                    if( success ) {
                        // 编程式导航
                        this.$router.push({name: 'login'});
                        return;
                    }
                    ElMessage({ message: `警告:${message}!`, type: 'warning'})
                }
            }).catch(reason =>{
                console.log(reason);
            });
        }
    }
}
</script>

<template>
    <div class="wrapper">
        <h3>用户注册</h3>
        <el-form label-position="left" label-width="80px">
            <el-form-item label="昵称">
                <el-input v-model="nickname" />
            </el-form-item>
            <el-form-item label="账号">
                <el-input v-model="account" />
            </el-form-item>
            <el-form-item label="登录密码">
                <el-input v-model="password" />
            </el-form-item>
            <el-form-item label="确认密码">
                <el-input v-model="confirm" />
            </el-form-item>
            <el-form-item label="">
                <el-button type="primary" @click="register">注册</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<style scoped>
:global(body) {
  background: #f4f4f4;
}
.wrapper{
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -15vw;
    margin-top: -155px;
    padding: 0 0.5vw;
    border-radius: 5px;
    background: #fff;
    width: 30vw;
    min-height: 310px;
}
</style>
